package com.cuntian.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.cuntian.contant.Constants;
import com.cuntian.dto.ModifyPwdDTO;
import com.cuntian.entity.User;
import com.cuntian.model.IMSessionInfo;
import com.cuntian.result.Result;
import com.cuntian.result.ResultUtils;
import com.cuntian.service.IUserService;
import com.cuntian.util.BeanUtils;
import com.cuntian.vo.UserVO;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {

    private final IUserService userService;

    // 获取当前用户信息
    @GetMapping("/self")
    public Result<UserVO> findSelfInfo() {
        IMSessionInfo session = (IMSessionInfo) StpUtil.getSession().get(Constants.USER_SESSION);
        User user = userService.getById(session.getUserId());
        UserVO userVO = BeanUtils.copyProperties(user, UserVO.class);
        return ResultUtils.success(userVO);
    }

    // 修改当前用户信息
    @PutMapping("/update")
    public Result<String> update(@Valid UserVO vo) {
        userService.update(vo);
        return ResultUtils.success("修改成功");
    }

    // 通过用户名查找用户
    @GetMapping("/findByName")
    public Result<List<UserVO>> findByName(@RequestParam String name) {
        return ResultUtils.success(userService.findUserByUserName(name));
    }

    // 通过id查询用户
    @GetMapping("/findByUid")
    public Result<UserVO> findByUid(@RequestParam Long uid){
        return ResultUtils.success(userService.findUserById(uid));
    }

    // 修改用户密码
    @PostMapping("/modifyPassword")
    public Result<String> modifyPassword(@Valid @RequestBody ModifyPwdDTO modifyPwdDTO){
        userService.modifyPassword(modifyPwdDTO);
        return ResultUtils.success("修改成功");
    }

}
